<script setup>
import {ref, reactive, onMounted} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {router} from "@/router/index.js";
import {Message, User} from "@element-plus/icons-vue";
import {userStore} from '@/store/index.js'

const userItemStore = userStore();
const activeName = ref('telephone');   //默认激活的tab
const loginForm = reactive({
  username: 'liboyang',
  password: '123456',
  code: '',
  key: '',
})
const isButtonDisabled = ref(false);
const refLoginForm = ref(null);
const userLogin = () => {
  // 发起登录请求
  refLoginForm.value.validate(valid => {
    if (valid) {
      axios.post('/users/login', loginForm).then(resp => {
        const user = resp.data;
        // 这里响应头大小写敏感，要写成小写
        localStorage.setItem('token', resp.headers.authorization);
        // 保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));
        //存储用户
        userItemStore.updateUser(user)
        //修改状态
        userItemStore.updateLoginStatus(true)
        // 提示登录成功
        ElMessage({
          message: `登录成功，欢迎您：${user.username}！`,
          type: 'success'
        });
        // 跳转到首页
        router.push('/');
      }).catch(error => {
        // 登录失败
        const messageText = error.response.data;
        ElMessage.error(`登录失败，${messageText}`);
      });
    } else {
      return false;
    }
    isButtonDisabled.value = true
    setTimeout(() => {
      isButtonDisabled.value = false;
    }, 5000);
  });
}

const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {min: 4, max: 4, message: '长度必须是4位', trigger: 'blur'}
  ]
});

const codeUrl = ref('');
const getCaptcha = () => {
  axios.get('/users/code').then(resp => {
    //返回两个数据：key是Redis中key，base64Img是图片
    codeUrl.value = resp.data.base64Img;
    loginForm.key = resp.data.key;
  })
}

const refSmsForm = ref(null);
const smsForm = reactive({
  phone: '18849045379',
  code: ''
});
const rulesPhone = reactive({
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {min: 4, max: 4, message: '长度必须是4位', trigger: 'blur'}
  ]
})


const smsDisabled = ref(false);  //发短信按钮是否可用
const smsText = ref('发送短信验证码');
const sendSms = () => {
  //验证手机号是否正确
  refSmsForm.value.validateField('phone', error => {
    //如果没有错误，则验证通过
    if (error) {
      //按钮不可用
      smsDisabled.value = true;
      //发送短信
      axios.get(`/users/sendSms/${smsForm.phone}`).then(resp => {
        //发送成功
        ElMessage({
          message: resp.data,
          type: 'success'
        });
      }).catch(error => {
        //发送失败
        ElMessage.error(error.response.data);
      }).finally(() => {
        //按钮文字变成倒计时
        let seconds = 15;
        smsText.value = `${seconds}秒后重新发送`;
        let timer = setInterval(() => {
          seconds--;
          if (seconds > 0) {
            smsText.value = `${seconds}秒后重新发送`;
          } else {
            //修改文字
            smsText.value = "发送短信验证码";
            //按钮可用
            smsDisabled.value = false;
            //清除定时器
            clearInterval(timer);
          }
        }, 1000);
      });
    }
  });
}
const smsLogin = ()=>{
  refSmsForm.value.validate(valid=>{
    if (valid){
      //编写登录逻辑
      axios.post('/users/smsLogin', smsForm).then(resp => {
        //获取到User对象
        const user = resp.data;
        //登录成功
        ElMessage({
          message:`登录成功，欢迎您：${user.username}`,
          type:'success'
        });
        //将后端返回的用户登录信息保存到store中
        userItemStore.updateUser(user)
        userItemStore.updateLoginStatus(true)

        //保存用户信息到本地浏览器中
        localStorage.setItem("user", JSON.stringify(user));
        //这里必须是小写
        localStorage.setItem("token", resp.headers['authorization']);
        //登录成功后跳转
        router.push('/');
      }).catch(error => {
        //登录失败
        ElMessage.error('登录失败，' + error.response.data);
      });
    }else{
      return false;
    }
  })
}


const goToRegister = () => {
  router.push("/register"); // 假设你有一个注册页面的路由
};


const smsEmail = ref('发送邮箱验证码');
const emailForm = reactive({
  email: '651670754@qq.com',  // 邮箱
  code: '',  // 验证码
})

const emailLogin = () => {
  refEmailForm.value.validate(valid => {
    if (valid) {
      axios.post('/users/emailLogin', emailForm).then(resp => {
        const user = resp.data;
        localStorage.setItem('token', resp.headers.authorization);
        localStorage.setItem('user', JSON.stringify(user));

        userItemStore.updateUser(user)
        userItemStore.updateLoginStatus(true)

        ElMessage({
          message: `登录成功，欢迎您：${user.username}！`,
          type: 'success'
        });
        router.push('/');
      }).catch(error => {
        const messageText = error.response.data;
        ElMessage.error(`登录失败，${messageText}`);
      });
    } else {
      return false;
    }
    isButtonDisabled.value = true
    setTimeout(() => {
      isButtonDisabled.value = false;
    }, 5000);
  });
}
const refEmailForm = ref(null);
const emailRules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度必须为4位', trigger: 'blur' }
  ]
})
const sendEmail=()=>{
  smsDisabled.value = true;
    axios.get(`/users/sendEmail/${emailForm.email}`).then(resp => {
      ElMessage({
        message: resp.data,
        type: 'success'
      });
    }).catch(error => {
      ElMessage.error(error.response.data);
    }).finally(() => {
      let seconds = 15;
      smsEmail.value = `${seconds}秒后重新发送`;
      let timer = setInterval(() => {
        seconds--;
        if (seconds > 0) {
          smsEmail.value = `${seconds}秒后重新发送`;
        } else {
          //修改文字
          smsEmail.value = "发送短信验证码";
          //按钮可用
          smsDisabled.value = false;
          //清除定时器
          clearInterval(timer);
        }
      }, 1000);
    });
}




onMounted(() => {
  getCaptcha();
})

</script>

<template>
  <div class="login-container">
    <el-tabs v-model="activeName" type="border-card" class="login-tabs">
      <!-- 用户名登录 -->
      <el-tab-pane label="用户名登录" name="userName">
        <el-card class="card">
          <h2 class="title">用户登录</h2>
          <el-form ref="refLoginForm" :model="loginForm" class="login-form"
                   :rules="rules" label-position="left"
                   label-width="80px">
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="loginForm.username"
                        placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input type="password" v-model="loginForm.password"
                        placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="loginForm.code"
                          maxlength="4"
                          minlength="4" placeholder="验证码"
                          style="width: 90px;">
                </el-input>
                <img :src="codeUrl"
                     style="cursor: pointer; margin-left: 10px;" @click="getCaptcha()"
                     title="看不清点击刷新"/>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;" type="primary"
                         @click="userLogin"
                         :disabled="isButtonDisabled">
                <el-icon><User/></el-icon>登录</el-button>
            </div>
          </el-form>
          <div class="register-link-container">
            <span>没有账号？</span>
            <el-link type="primary" @click="goToRegister">去注册</el-link>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 手机号登录 -->
      <el-tab-pane label="手机号登录" name="telephone">
        <el-card class="card">
          <h2 class="title">手机号登录</h2>
          <el-form ref="refSmsForm" :model="smsForm"
                   class="login-form" :rules="rulesPhone"
                   label-position="left"
                   label-width="80px">
            <el-form-item label="手机号：" prop="phone">
              <el-input v-model="smsForm.phone"
                        placeholder="请输入手机号">
                <template #suffix>
                  <el-icon><Iphone/></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="smsForm.code" maxlength="4"
                          minlength="4" placeholder="验证码"
                          style="width: 90px; margin-right: 10px;">
                </el-input>
                <el-button type="text" :disabled="smsDisabled"
                           @click="sendSms">
                  <el-icon :size="20"><Message/></el-icon>
                  {{ smsText }}
                </el-button>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;"
                         type="primary" @click="smsLogin">
                <el-icon><User/></el-icon>登录</el-button>
            </div>
          </el-form>
          <div class="register-link-container">
            <span>*如果您没有账户,登录时我们将自动为您注册</span>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 邮箱登录 -->
      <el-tab-pane label="邮箱登录" name="emailLogin">
        <el-card class="card">
          <h2 class="title">邮箱登录</h2>
          <el-form ref="refEmailForm" :model="emailForm" class="login-form"
                   :rules="emailRules" label-position="left" label-width="80px">
            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="emailForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="emailForm.code" maxlength="4" minlength="4" placeholder="验证码" style="width: 90px;"></el-input>
                <el-button type="text" :disabled="smsDisabled"
                           @click="sendEmail">
                  <el-icon :size="20"><Message/></el-icon>
                  {{ smsEmail }}
                </el-button>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;" type="primary" @click="emailLogin" :disabled="isButtonDisabled">
                <el-icon><User /></el-icon>登录
              </el-button>
            </div>
          </el-form>
          <div class="register-link-container">
            <span>*如果您没有账户,登录时我们将自动为您注册</span>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.login-container {
  height: 100vh;
  background: url('http://smh25828x.hn-bkt.clouddn.com/imgs/60.jpg') no-repeat center center fixed;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  margin-top: 20px;
  width: 450px;
  height: 430px;
  padding: 15px;
  background-color: white; /* 表单区域背景白色 */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  border-radius: 8px;
}

.title {
  margin-top: 10px;
  font-size: 25px;
  text-shadow: 2px 2px 4px #888;
  text-align: center;
}

.login-form {
  max-width: 300px;
  margin: 0 auto;
}

.login-btn-container {
  text-align: center;
  margin-bottom: 30px;
}

.form-item-container {
  display: flex;
  align-items: flex-end;
}
.register-link-container {
  text-align: center;
  margin-top: 20px;
}

.register-link-container span {
  font-size: 14px;
  color: #888;
}

.register-link-container .el-link {
  font-size: 14px;
  color: #409EFF;
}
/* 确保 Tab 和 内容区域统一 */
.login-tabs .el-tabs__content {
  display: flex;
  justify-content: center;
}

.card {
  width: 100%;
  max-width: 450px;
}
</style>
